﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using org.project.web.utils;
using System.Configuration;
using System.Text;
using System.Data;

public partial class hunter : System.Web.UI.Page
{
    public volatile String ConnectionString = ConfigurationManager.ConnectionStrings["projectConnectionString"].ConnectionString;
    private String GPServName = "";


    protected void Page_Load(object sender, EventArgs e)
    {
       
        WGYearTextBox.Text = Convert.ToString(DateTime.Now.Year);
        //驗證
        WGYearTextBoxRangeValidator.MaximumValue = Convert.ToString(DateTime.Now.Year);
        WGBudgetRangeValidator.MaximumValue = Convert.ToString(int.MaxValue);

        WStartTextBox.Text = Convert.ToString(DateTime.Now.ToShortDateString());
        WEndTextBox.Text = Convert.ToString(DateTime.Now.AddDays(3).ToShortDateString());

        //MIdTextBox.Text = (String)Session["MId"];
        MNameTextBox.Text = Session["User"].ToString();

    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (savefile(PictureFileUpload) != true)
            {
                Label1.Text = "您沒有指定檔案";
            }


        }
        catch (Exception ex) {
            Label1.Text = "發生錯誤: " + ex.Message;
        }

        //預設圖片
        int WGPId = 1;

        if (!GPServName.Equals(""))
        {

            SQLUtility prequery_utiity = new SQLUtility();
            String GoodsPicSqlQuery = "Select * from GoodsPic Where GPServName ='" + GPServName+"'";
            
            //DataSet GoodsPicDataset = new DataSet();


            //prequery_utiity.UseSqlDataAdapterExecuteCommand(ConnectionString, GoodsPicSqlQuery, ref GoodsPicDataset);
            List<Dictionary<String, Object>> result = prequery_utiity.ExecuteCommand(ConnectionString, GoodsPicSqlQuery);
            //WGPId = result.Single().Values.ElementAt(0).ToString();
            WGPId = Convert.ToInt32(result.Single().ElementAt(0).Value);

            //GoodsPicListView.DataSource = GoodsPicDataset;
            //GoodsPicListView.DataBind();


            //Dictionary<String, Object> rowsData = resultList.ToList()[0].Values[0];
            //轉陣列然後再取得值(Field 1)
            //WGPId = (String)GoodsPicListView.Items[0].DataItem;
            //WGPId = (String)(Good.Single().Values.ElementAt(0));
            //WGPId = rowsData.Value.ToString();
        }
        

        //String WGPId = rowsData[GPServName].ToString();






        //將通緝令新增到資料庫
        //MyWantedSqlDataSource.InsertCommand = 
        SQLUtility utiity = new SQLUtility();
        
        /*
        String insertWantedSql = "INSERT INTO Wanted(WStart, WEnd, MId, HCId, WTran, WVisible, GCId, WGPId, WGApp, WGAmount, WGName, WGDescription, WGYear, WGBrand, WGMadeIn, WGBudget, WNote)"
                                         + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        */
        //cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);


        ListItemCollection items = WTranListBox.Items;
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < items.Count;i++ )
        {
            if (items[i].Selected) {
                content.Append(items[i].Value);
                content.Append("、");
            }
        }

        //String[] ParametersValues = new String[17];

        //資料資自動新增
        //String WId = "1";

        String WStart = DateTime.Now.ToShortDateString();
        String WEnd = DateTime.Now.AddDays(3).ToShortDateString();
        String MId = Session["MId"].ToString();

        //String MId = "1";
        //預設狀態 (交涉中)
        String HCId = "1";
        String WTran = content.ToString();
        String WVisible = "true";
        String GCId = GCThirdDropDownList.SelectedValue;
        ///
        //從資料庫查詢到的 GPId
        //WGPId = "3";
        String WGApp = WGAppTextBox.Text;
        String WGAmount = WGAmountTextBox.Text;
        String WGName = WGNameTextBox.Text;
        String WGDescription = WGDescriptionTextBox.Text;
        int year = Convert.ToInt32(WGYearTextBox.Text);
        int month = Convert.ToInt32(WGMonthTextBoxDropDownList.SelectedValue);

        String WGYear = new DateTime(year,month, 1).ToShortDateString();

        String WGBrand = WGBrandTextBox.Text;
        String WGMadeIn = WGMadeInTextBox.Text;
        String WGBudget = WGBudgetTextBox.Text;
        //ParametersValues[16] = WNoteWNoteTextBox.Text;
        String WNote = "";

        String insertWantedSql = "INSERT INTO Wanted(WStart, WEnd, MId, HCId, WTran, WVisible, GCId, WGPId, WGApp, WGAmount, WGName, WGDescription, WGYear, WGBrand, WGMadeIn, WGBudget, WNote)"
                                         +" VALUES ('" + WStart + "','" + WEnd + "','" + MId + "','" + HCId +"','"+ WTran + "','" + WVisible + "','" + GCId + "','"+ WGPId + "','" + WGApp + "','"+ WGAmount + "','" + WGName + "','" + WGDescription +"','" + WGYear + "','" + WGBrand + "','" + WGMadeIn + "','" + WGBudget + "','" + WNote + "')";

        String queryWantedSql = "Select * from Wanted Where MId="+MId;

        int insertRows = utiity.ExecuteCommandNonQuery(ConnectionString, insertWantedSql);
        DataSet dataset = new DataSet();
        utiity.UseSqlDataAdapterExecuteCommand(ConnectionString, queryWantedSql, ref dataset);
        WantedGridView.DataSource = dataset;
        WantedGridView.DataBind();

        Response.Write("<script >alert('通緝令發布完成！');</script>");

    }
    bool savefile(FileUpload Uploading)
    {
        //若有檔案即進行存檔
        if (Uploading.HasFile == true)
        {
            //=================== 處理上傳檔案 ===================

            //ServerFilename 變數為照片在伺服器上的檔名
            string ServerFilename;
            //ServerPathFilename 變數為照片在伺服器上的絕對路徑
            string ServerPathFilename;

            //Guid 類別的 NewGuid 方法可產生具唯一性的字串, 作為照片的檔名
            //System.IO.Path.GetExtension 方法可取得上傳檔案的副檔名
            ServerFilename = Guid.NewGuid().ToString() +
               System.IO.Path.GetExtension(Uploading.FileName).ToLower();

            //Page.MapPath() 方法可以取得檔案或目錄在伺服器上的絕對路徑
            ServerPathFilename = Page.MapPath("~/photo/") + ServerFilename;

            //將上傳的檔案儲存到 ServerPathFilename 所指定的路徑
            Uploading.SaveAs(ServerPathFilename);

            //加總上傳的檔案數及檔案位元組


            //=================== 製作縮圖 ===================

            //縮圖寬高上限
            int MaxLength = 200;
            //縮圖寬度
            int ThumbWidth;
            //縮圖高度
            int ThumbHeight;

            //以 System.Drawing.Image 類別建立 Photo 物件, 
            //然後將原始圖讀入 Photo 物件
            System.Drawing.Image Photo = System.Drawing.Image.FromFile(ServerPathFilename);

            //計算縮圖的寬度與高度
            if (Photo.Width > Photo.Height)
            {
                ThumbWidth = MaxLength;
                ThumbHeight = Convert.ToInt32(Convert.ToSingle(Photo.Height) / Convert.ToSingle(Photo.Width) * MaxLength);
            }
            else
            {
                ThumbHeight = MaxLength;
                ThumbWidth = Convert.ToInt32(Convert.ToSingle(Photo.Width) / Convert.ToSingle(Photo.Height) * MaxLength);
            }

            //以 Bitmap 類別建立 Thumb 物件, 以存放縮圖
            Bitmap Thumb = new Bitmap(Photo, ThumbWidth, ThumbHeight);

            //將縮圖儲存到伺服器上
            Thumb.Save(Page.MapPath("~/thumb/") + ServerFilename);

            //=================== 寫入資料庫 ===================

            //將伺服器檔名與照片名稱指定給 SqlDataSource1 Insert 陳述式的參數
            GCPic.InsertParameters["GPServName"].DefaultValue = ServerFilename;
            GCPic.InsertParameters["GPName"].DefaultValue = Uploading.FileName;

            //將圖片名稱先用變數暫存，之後要新增通緝令時一用這個查詢到它的 GPId 才能一起新增到通緝令的資料表格
            GPServName = GCPic.InsertParameters["GPServName"].DefaultValue;
            
            //將伺服器檔名與照片名稱寫入資料庫
            GCPic.Insert();

            return true;
        }
        else
        {
            return false;
        }
    }
    protected void MyWantedButton_Click(object sender, EventArgs e)
    {

    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["MId"] == null)//會員
        {
            this.Page.MasterPageFile = "~/MasterPage.master";
            Response.Redirect("login.aspx");
        }
        else       //一般使用者
            this.Page.MasterPageFile = "~/LoginedMasterPage.master";
    }
}